package com.yang.consumer.kafka.boot.config;

import com.yang.consumer.kafka.boot.config.KafkaConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 *
 * @author yang
 */
@Component
@Slf4j
public class KafkaConsumer {

    /**
     * 不同消费组互不影响（同一个分区，可以被不同消费组同时消费）
     * 但是一个分区只能被消费组内一个消费者所消费
     * topics 主题名称
     * groupId 消费组id
     * @param record
     * @param ack
     * @param topic
     */
    @KafkaListener(topics = KafkaConfig.TOPIC_TEST, groupId = KafkaConfig.TOPIC_GROUP1)
    public void topic_test(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test 消费了： Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }

    @KafkaListener(topics = KafkaConfig.TOPIC_TEST, groupId = KafkaConfig.TOPIC_GROUP2)
    public void topic_test1(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test1 消费了： Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }
}